//
//  ZhifuViewController.swift
//  联付商圈
//
//  Created by zhangqi on 2017/8/10.
//  Copyright © 2017年 lianfu. All rights reserved.
//

import UIKit


import Kingfisher
import Alamofire

class ZhifuViewController: UIViewController {
    var titleArray = ["订单编号:","订单金额:"]
    var zhifufangshi = ["支付宝","余额"]
    var zhifuLabel = ["支付宝支付","余额支付"]
    var CYView = CYPasswordView()
    @IBOutlet weak var zhifuTableView: UITableView!

    
    func requesrali(){
        let pa = ["ddh":ddh]
        let urlString = "https://www.beidikeji.com/life/public/jiekou/zhifubao?"
        let manager = Alamofire.SessionManager.default
        manager.session.configuration.timeoutIntervalForRequest = 45
        manager.request(urlString,method:.post, parameters: pa).responseJSON {Request in
            switch Request.result {
            case .success:
                let json = JSON(data: Request.data!)
                let ord = json.string!
                self.ali(orderString: ord)
            case .failure:
                self.noticeInfo("未知错误", autoClear: true, autoClearTime: 1)
            }
        }
    }
    
    func ali(orderString:String){
            AlipaySDK.defaultService().payOrder(orderString, fromScheme: "lianfushangquan", callback: { (resultDic) in
                let re = resultDic! as! [String:String]
                let rere = re["resultStatus"]
                if rere == "\(9000)" {
                    //print("交易成功")
                    self.noticeSuccess("支付成功", autoClear: true, autoClearTime: 2)
                    let sb = UIStoryboard(name: "Main", bundle:nil)
                    let secondViewController = sb.instantiateViewController(withIdentifier: "DingdanXiangqingViewController") as! DingdanXiangqingViewController
                    self.navigationController?.pushViewController(secondViewController, animated: true)
                } else {
                    //print("交易失败")
                }
                
            })
    }
    
    
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        zhifuTableView.tableFooterView = UIView(frame: CGRect.zero)
        // Do any additional setup after loading the view.
        NotificationCenter.default.addObserver(self, selector: #selector(forget), name: NSNotification.Name.CYPasswordViewForgetPWDButtonClick, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(cancel), name: NSNotification.Name.CYPasswordViewCancleButtonClick, object: nil)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    func yuezhifu(){
        
        let alertVC = UIAlertController(title: "余额支付", message: "支付" + "\(zonghjia)" + "元", preferredStyle: UIAlertControllerStyle.alert)
        let acSure = UIAlertAction(title: "确定", style: UIAlertActionStyle.destructive) { (UIAlertAction) -> Void in
            
            self.CYView = CYPasswordView()
            let keyWindow = UIApplication.shared.keyWindow!
            self.CYView.show(in: keyWindow)
            self.CYView.finish = {
                password -> Void in
                let x = password
                //print(x!)
                self.yanzhengmima(mima:"\(x!)")
            }

            
        }
        let acCancel = UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel) { (UIAlertAction) -> Void in
            return
        }
        alertVC.addAction(acSure)
        alertVC.addAction(acCancel)
        self.present(alertVC, animated: true, completion: nil)
    }
    
    func yezf(){
        let x = UserDefaults.standard.object(forKey: "userInfo") as! NSDictionary
        let y = x["name"]!
        let pa = ["name":"\(y)","ddh":ddh]
        let urlString = "https://www.beidikeji.com/life/public/jiekou/yuepay?"
        let manager = Alamofire.SessionManager.default
        manager.session.configuration.timeoutIntervalForRequest = 45
        manager.request(urlString,method:.post,parameters: pa).responseJSON {Request in
            switch Request.result {
            case .success:
                
                let json = JSON(data: Request.data!).dictionaryObject!
                //print(json)
                for t in json.keys{
                    let a = t
                    if a == "error" {
                        //print(json)
                        let x = json["error"] as! [String:Any]
                        let y = "\(x["code"]!)"
                        //print(y)
                        if y == "\(8000)" {
                            self.tanchuang()
                        } else {
                        self.noticeInfo("支付失败", autoClear: true, autoClearTime: 2)
                        }
                        return
                    } else if a == "success" {
                        self.noticeSuccess("支付成功", autoClear: true, autoClearTime: 2)
                        let sb = UIStoryboard(name: "Main", bundle:nil)
                        let secondViewController = sb.instantiateViewController(withIdentifier: "DingdanXiangqingViewController") as! DingdanXiangqingViewController
                        self.navigationController?.pushViewController(secondViewController, animated: true)                    }
                }

            case .failure:
                self.noticeInfo("未知错误", autoClear: true, autoClearTime: 1)
            }
        }
    }
    
    func forget(){
        self.noticeInfo("退出账号重新登录", autoClear: true, autoClearTime: 1)
    }
    func cancel(){
        //print("取消输入密码")
    }
    
    func yanzhengmima(mima:String){
        let x = UserDefaults.standard.object(forKey: "userInfo") as! NSDictionary
        let y = x["name"]!
        let par = ["name":"\(y)","zfmm":mima]
        let urlString = "https://www.beidikeji.com/life/public/jiekou/zfmm?"
        let manager = Alamofire.SessionManager.default
        manager.session.configuration.timeoutIntervalForRequest = 45
        manager.request(urlString,method:.post,parameters: par).responseJSON {Request in
            switch Request.result {
            case .success:
                let json = JSON(data: Request.data!).dictionaryObject!
                //print(json)
                for t in json.keys{
                    let a = t
                    if a == "error" {
                        self.noticeInfo("密码验证错误", autoClear: true, autoClearTime: 1)
                        self.CYView.hide()
                        return
                    } else if a == "success" {
                        self.CYView.removeFromSuperview()
                        self.yezf()
                    }
                }
            case .failure:
                self.noticeInfo("未知错误", autoClear: true, autoClearTime: 1)
                self.CYView.hide()
            }
        }
    }
    
    func tanchuang(){
        let alertVC = UIAlertController(title: "支付失败", message: "不能购买自己所属店的商品，或者余额不足", preferredStyle: UIAlertControllerStyle.alert)
        let acCancel = UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel) { (UIAlertAction) -> Void in
            return
        }
        alertVC.addAction(acCancel)
        self.present(alertVC, animated: true, completion: nil)
    }



}



extension ZhifuViewController: UITableViewDelegate,UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch section {
        case 0:
            return 2
        case 1:
            return 2
        default:
            break
        }
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        
        
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "ZhifudingdanTableViewCell", for: indexPath) as! ZhifudingdanTableViewCell
            let x = [ddh,"\(zonghjia)"]
            cell.numLabel.text = x[indexPath.row]
            cell.titleLabel.text = titleArray[indexPath.row]
            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "ZhifufangshiTableViewCell", for: indexPath) as! ZhifufangshiTableViewCell
            cell.fangshiImage.image = UIImage(named:zhifufangshi[indexPath.row])
            cell.nameLabel.text = zhifuLabel[indexPath.row]
            cell.senameLabel.text = ""
            return cell
        }
    }
    
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 1 {
            return 80
        } else {
            return 44
        }
    }
    
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
            return 20
        
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        zhifuTableView.deselectRow(at: indexPath, animated: false)
        if indexPath.section == 1 && indexPath.row == 0 {
            requesrali()
        } else if indexPath.section == 1 && indexPath.row == 1 {
            yuezhifu()
//            let sb = UIStoryboard(name: "Main", bundle:nil)
//            let secondViewController = sb.instantiateViewController(withIdentifier: "JiluViewController") as! JiluViewController
//            self.navigationController?.pushViewController(secondViewController, animated: true)
        }
        
    }
}

